<?php

namespace App\Admin\Controllers\OwnerItem;

use App\Models\HouseFeeConfig;
use App\Models\Owner;
use App\Models\OwnerItem;
use App\Services\MeterService;
use App\Services\OwnerItemService;
use Carbon\Carbon;
use Dcat\Admin\Grid;
use Dcat\Admin\IFrameGrid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Widgets\Alert;

// 待抄表
class MeterReadingController extends CommonOwnerItemController
{
    protected $ownerItemService;
    protected $meterService;

    public function __construct(OwnerItemService $ownerItemService, MeterService $meterService)
    {
        $this->ownerItemService = $ownerItemService;
        $this->meterService = $meterService;
    }

    public function index(Content $content)
    {
        if (request(IFrameGrid::QUERY_NAME)) {
            return $content->perfectScrollbar()->body($this->iFrameGrid());
        }

        $info = '<i class="fa fa-exclamation-circle"></i> 如果未填写杂费（比如：水费，电费），系统不会发送缴费通知给租客';

        return $content
            ->title($this->title())
            ->description($this->description()['index'] ?? trans('admin.list'))
            ->body(Alert::make($info)->info())
            ->body($this->grid());
    }

    protected $title = "未抄表账单";

    protected function customGrid(Grid $grid)
    {
        $meterService = $this->meterService;
        $grid->other_amount('杂费')->display(
            function ($value) {
                return $value ? $value : "未填写";
            }
        )->modal(
            '杂费列表',
            function () {
                $owner = Owner::query()->find($this->owner_id);
                if ($owner->config) {
                    $input = "";
                    foreach ($owner->config as $item) {
                        $config = HouseFeeConfig::query()->find($item['house_config_id']);
                        $input .= <<< HTML
        <div class="input-group mb-3">
          <div class="input-group-prepend">
            <span class="input-group-text">请输入本期{$config->name}费（{$item['price']}元/{$config['unit']}）</span>
          </div>
          <input type="text" name="{$config->id}" class="form-control" aria-label="Amount (to the nearest dollar)">
          <div class="input-group-append">
            <span class="input-group-text">￥</span>
          </div>
        </div>
HTML;
                    }

                    $url = route('admin.running-water.update-other-amount', ['bill' => $this->id]);
                    $_token = csrf_token();

                    return <<< HTML
<div style='padding:10px 10px 0'>
    <div class="alert alert-primary" role="alert">请注意：当前为测试版，还没有抄表功能，所以这里直接填写本周期各项杂项的价格</div>
    <div>
        <form action="{$url}" method="post">
        <input type="hidden" name="_token" value="{$_token}">
        {$input}
        <button type="submit" class="btn btn-primary">提交</button>
        </form>
    </div>
</div>
HTML;

                }
            }
        );

//        $grid->other_amount('抄表')->display(function ($value) {
//            return $value ? $value : "未填写";
//        })->modal('抄表列表', function () use ($meterService) {
//            $owner = Owner::query()->find($this->owner_id);
//            $input = "";
//
//            foreach ($owner->config as $key => $item) {
//                $config = HouseFeeConfig::query()->find($item['house_config_id']);
//                // 获取上一次的抄表对象
//                if ($this->total_amount) {  // 如果已经存在本期流水总金额，那么表示是更新抄表数据
//                    $lastMeter = $meterService->getLastLastMeterByOwner($owner, $config);
//                } else {
//                    $lastMeter = $meterService->getLastMeterByOwner($owner, $config);
//                }
//
//                $input .= <<< HTML
//                    <tr>
//                        <td>{$config->name}表</td>
//                        <td>{$lastMeter->value}</td>
//                        <td>
//                            <label>
//                                <input name="{$owner->id}" value="">
//                            </label>
//                        </td>
//                        <td>0</td>
//                    </tr>
//HTML;
//            }
//
//            $url = route('admin.running-water.update-meter', ['bill' => $this->id]);
//            $_token = csrf_token();
//            return <<< HTML
//<div style='padding:10px 10px 0'>
//    <div>
//     <form action="{$url}" method="post">
//        <input type="hidden" name="_token" value="{$_token}">
//        <div class="modal-body">
//                <div class="alert alert-primary" role="alert">金额 = (本期表读数 - 上期表读数) * 单价</div>
//                <div>
//                    <div class="input-group mb-3">
//                        <table class="table">
//                            <thead>
//                            <tr>
//                                <th scope="col">名称</th>
//                                <th scope="col">上期表读数</th>
//                                <th scope="col">本期表读数</th>
//                                <th scope="col">金额</th>
//                            </tr>
//                            </thead>
//                            <tbody>
//                                {$input}
//                            </tbody>
//                        </table>
//                    </div>
//                </div>
//            </div>
//            <div class="modal-footer">
//                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
//                <button type="submit" class="btn btn-primary">提交</button>
//            </div>
//        </form>
//    </div>
//</div>
//HTML;
//        });
    }

    public function updateOtherAmount(OwnerItem $bill)
    {
        $boolean = $this->ownerItemService->updateOtherAmount($bill);
        if ($boolean) {
            admin_success("更新杂费成功！");
        } else {
            admin_error("更新杂费失败！");
        }

        return \response()->redirectTo(route('admin.meter-reading.index'));
    }

    protected function customDetail($show)
    {
    }

    protected function map(): array
    {
        return [
            ['total_amount', '=', null],
            ['started_at', '<', Carbon::now()],
        ];
    }
}
